#pragma once

#include <iostream>
#include <thread>
#include "udp_sock.hpp"

class UdpClient
{
public:
    UdpClient(std::string ip, uint16_t port)
        : _ip(ip), _port(port), _sock()
    {
        memset(&_peer, 0, sizeof(_peer));
        _peer.sin_family = AF_INET;
        _peer.sin_port = htons(_port);
        _peer.sin_addr.s_addr = inet_addr(_ip.c_str());
    }
    ~UdpClient() {}

    void Init()
    {
        _sock.Socket();
    }

    void Start()
    {
        // 1. 发送数据
        std::thread sd(&UdpClient::Send, this);
        // 2. 接受数据
        std::thread rd(&UdpClient::Recv, this);
        sd.join();
        rd.join();
    }

private:
    void Send()
    {
        while (true)
        {
            std::string msg;
            std::cout << "Please Enter# ";
            std::cin >> msg;

            _sock.Send(msg, _peer, sizeof(_peer));
        }
    }

    void Recv()
    {
        while (true)
        {
            std::string echo_msg;
            socklen_t len = sizeof(_peer);
            _sock.Recv(&echo_msg, &_peer, &len);
            // 3. 显示数据
            std::cout << "server echo# " << echo_msg << std::endl;
        }
    }

private:
    UdpSock _sock;
    uint16_t _port;
    std::string _ip;
    struct sockaddr_in _peer;
};